import { defineComponent, onMounted, onUnmounted, ref } from "vue";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import "./CityScene3D.css";

interface Vehicle {
  mesh: THREE.Group;
  speed: number;
  baseSpeed: number;
  direction: THREE.Vector3;
  lane: { road: number; direction: "forward" | "backward"; isHorizontal: boolean };
  isStopped: boolean;
}

interface TrafficLight {
  mesh: THREE.Group;
  state: "red" | "yellow" | "green";
  timer: number;
  position: THREE.Vector3;
  controlsHorizontal: boolean;
}

export default defineComponent({
  name: "CityScene3D",
  setup() {
    const containerRef = ref<HTMLDivElement | null>(null);
    let scene: THREE.Scene;
    let camera: THREE.PerspectiveCamera;
    let renderer: THREE.WebGLRenderer;
    let controls: OrbitControls;
    let animationId: number;
    const vehicles: Vehicle[] = [];
    const trafficLights: TrafficLight[] = [];

    const ROADS = [-240, -80, 80, 240];
    const ROAD_WIDTH = 20;
    const SAFE_DISTANCE = 15; // 车辆安全距离 - 更符合实际车距
    const MIN_VEHICLE_SPACING = 25; // 初始化时车辆最小间距

    // 创建科技园区建筑
    const createParkBuildings = () => {
      const buildings: THREE.Mesh[] = [];

      const buildingBlocks = [
        // 西北区域 - 研发中心
        { x: -300, z: -300, w: 50, h: 80, d: 50, color: 0x4a90e2, label: "研发中心A" },
        { x: -200, z: -300, w: 45, h: 75, d: 45, color: 0x5c9fd6, label: "研发中心B" },
        { x: -300, z: -200, w: 48, h: 70, d: 48, color: 0x6ba8de, label: "研发中心C" },
        { x: -200, z: -200, w: 46, h: 68, d: 46, color: 0x7ab8e8, label: "研发中心D" },

        { x: -180, z: -300, w: 42, h: 65, d: 42, color: 0x89c7f2, label: "实验楼A" },
        { x: -120, z: -300, w: 44, h: 62, d: 44, color: 0x98d6fc, label: "实验楼B" },
        { x: -180, z: -180, w: 40, h: 60, d: 40, color: 0x5a9ed5, label: "实验楼C" },
        { x: -120, z: -180, w: 38, h: 58, d: 38, color: 0x6caede, label: "实验楼D" },
        { x: -180, z: -120, w: 41, h: 55, d: 41, color: 0x7ebee7, label: "测试中心A" },
        { x: -120, z: -120, w: 39, h: 52, d: 39, color: 0x8fcef1, label: "测试中心B" },

        // 东北区域 - 生产厂房
        { x: 300, z: -300, w: 50, h: 50, d: 50, color: 0x90a4ae, label: "生产车间A" },
        { x: 200, z: -300, w: 45, h: 48, d: 45, color: 0x78909c, label: "生产车间B" },
        { x: 300, z: -200, w: 48, h: 45, d: 48, color: 0xa0aab5, label: "生产车间C" },
        { x: 200, z: -200, w: 46, h: 42, d: 46, color: 0x8d98a3, label: "生产车间D" },

        { x: 120, z: -300, w: 42, h: 40, d: 42, color: 0xb0bec5, label: "仓储A" },
        { x: 180, z: -300, w: 44, h: 38, d: 44, color: 0xc8d4db, label: "仓储B" },
        { x: 120, z: -180, w: 40, h: 36, d: 40, color: 0x9fa8b0, label: "仓储C" },
        { x: 180, z: -180, w: 38, h: 35, d: 38, color: 0xadb6bd, label: "仓储D" },
        { x: 120, z: -120, w: 41, h: 42, d: 41, color: 0xbbc4cb, label: "物流中心A" },
        { x: 180, z: -120, w: 39, h: 40, d: 39, color: 0xc9d2d9, label: "物流中心B" },

        // 西南区域 - 办公楼
        { x: -300, z: 300, w: 50, h: 90, d: 50, color: 0xffa726, label: "总部大楼" },
        { x: -200, z: 300, w: 45, h: 85, d: 45, color: 0xffb74d, label: "行政楼A" },
        { x: -300, z: 200, w: 48, h: 82, d: 48, color: 0xffc875, label: "行政楼B" },
        { x: -200, z: 200, w: 46, h: 78, d: 46, color: 0xffd89c, label: "办公楼A" },

        { x: -180, z: 300, w: 40, h: 75, d: 40, color: 0xffe0b2, label: "办公楼B" },
        { x: -120, z: 300, w: 38, h: 72, d: 38, color: 0xffeccc, label: "办公楼C" },
        { x: -180, z: 180, w: 42, h: 70, d: 42, color: 0xffb74d, label: "会议中心" },
        { x: -120, z: 180, w: 40, h: 68, d: 40, color: 0xffc875, label: "培训中心" },
        { x: -180, z: 120, w: 39, h: 65, d: 39, color: 0xffd89c, label: "商务中心A" },
        { x: -120, z: 120, w: 41, h: 62, d: 41, color: 0xffe0b2, label: "商务中心B" },

        // 东南区域 - 综合服务区
        { x: 300, z: 300, w: 50, h: 55, d: 50, color: 0x66bb6a, label: "餐饮中心" },
        { x: 200, z: 300, w: 45, h: 52, d: 45, color: 0x81c784, label: "员工宿舍A" },
        { x: 300, z: 200, w: 48, h: 50, d: 48, color: 0x9ccc9c, label: "员工宿舍B" },
        { x: 200, z: 200, w: 46, h: 48, d: 46, color: 0xaed5ae, label: "员工宿舍C" },

        { x: 120, z: 300, w: 42, h: 45, d: 42, color: 0xc5e1a5, label: "活动中心" },
        { x: 180, z: 300, w: 44, h: 42, d: 44, color: 0xdcedc8, label: "健身中心" },
        { x: 120, z: 180, w: 40, h: 40, d: 40, color: 0x9ccc9c, label: "便利店" },
        { x: 180, z: 180, w: 38, h: 38, d: 38, color: 0xaed5ae, label: "医务室" },
        { x: 120, z: 120, w: 41, h: 42, d: 41, color: 0xc5e1a5, label: "快递中心" },
        { x: 180, z: 120, w: 39, h: 40, d: 39, color: 0xdcedc8, label: "服务中心" },

        // 中心区域 - 避开湖泊和高架桥路径
        { x: 0, z: -180, w: 44, h: 95, d: 44, color: 0x7e57c2, label: "展示中心" },
        { x: 0, z: -120, w: 42, h: 88, d: 42, color: 0x9575cd, label: "访客中心" },

        { x: 50, z: 0, w: 38, h: 60, d: 38, color: 0xba68c8, label: "数据中心" },

        { x: 0, z: 120, w: 41, h: 70, d: 41, color: 0xce93d8, label: "创新中心" },
        { x: 0, z: 180, w: 39, h: 65, d: 39, color: 0xe1bee7, label: "孵化中心" },
      ];

      buildingBlocks.forEach((buildingData) => {
        const geometry = new THREE.BoxGeometry(
          buildingData.w,
          buildingData.h,
          buildingData.d
        );

        const material = new THREE.MeshPhongMaterial({
          color: buildingData.color,
          emissive: new THREE.Color(buildingData.color),
          emissiveIntensity: 0.1,
          shininess: 80,
          transparent: true,
          opacity: 0.95,
        });

        const building = new THREE.Mesh(geometry, material);
        building.position.set(
          buildingData.x,
          buildingData.h / 2,
          buildingData.z
        );

        const edges = new THREE.EdgesGeometry(geometry);
        const lineMaterial = new THREE.LineBasicMaterial({
          color: 0xffffff,
          transparent: true,
          opacity: 0.4,
        });
        const lineSegments = new THREE.LineSegments(edges, lineMaterial);
        building.add(lineSegments);

        const floors = Math.floor(buildingData.h / 4);
        for (let i = 0; i < floors; i++) {
          const windowGeometry = new THREE.PlaneGeometry(
            buildingData.w * 0.85,
            3
          );
          const windowMaterial = new THREE.MeshBasicMaterial({
            color: 0xffee88,
            transparent: true,
            opacity: Math.random() * 0.5 + 0.3,
            side: THREE.DoubleSide,
          });
          const window1 = new THREE.Mesh(windowGeometry, windowMaterial);
          window1.position.set(0, -buildingData.h / 2 + i * 4 + 2, buildingData.d / 2 + 0.1);
          building.add(window1);

          const window2 = window1.clone();
          window2.position.set(0, -buildingData.h / 2 + i * 4 + 2, -buildingData.d / 2 - 0.1);
          building.add(window2);
        }

        scene.add(building);
        buildings.push(building);
      });

      return buildings;
    };

    // 创建园区中心不规则湖泊
    const createLake = () => {
      // 湖泊位于西南象限的空地，避开所有道路和建筑
      // 在道路 x=-240和-80之间，z=80和240之间的区域
      const lakeShape = new THREE.Shape();

      // 湖泊中心位置：x=-160, z=160（完全避开道路和建筑）
      const centerX = -160;
      const centerZ = 160;

      // 创建有机形状的湖泊轮廓（尺寸适中，确保不触碰道路）
      lakeShape.moveTo(centerX - 35, centerZ - 25);
      lakeShape.bezierCurveTo(
        centerX - 42, centerZ - 18,
        centerX - 45, centerZ + 5,
        centerX - 38, centerZ + 28
      );
      lakeShape.bezierCurveTo(
        centerX - 25, centerZ + 40,
        centerX + 15, centerZ + 42,
        centerX + 35, centerZ + 32
      );
      lakeShape.bezierCurveTo(
        centerX + 48, centerZ + 20,
        centerX + 46, centerZ - 8,
        centerX + 32, centerZ - 22
      );
      lakeShape.bezierCurveTo(
        centerX + 15, centerZ - 30,
        centerX - 8, centerZ - 32,
        centerX - 35, centerZ - 25
      );

      const lakeGeometry = new THREE.ShapeGeometry(lakeShape);
      const lakeMaterial = new THREE.MeshPhongMaterial({
        color: 0x1e88e5,
        transparent: true,
        opacity: 0.8,
        shininess: 120,
        side: THREE.DoubleSide,
      });
      const lake = new THREE.Mesh(lakeGeometry, lakeMaterial);
      lake.rotation.x = -Math.PI / 2;
      lake.position.set(0, 0.05, 0);
      scene.add(lake);

      // 湖岸绿化带
      const bankShape = new THREE.Shape();
      const bankWidth = 5;

      bankShape.moveTo(centerX - 35 - bankWidth, centerZ - 25 - bankWidth);
      bankShape.bezierCurveTo(
        centerX - 42 - bankWidth, centerZ - 18,
        centerX - 45 - bankWidth, centerZ + 5,
        centerX - 38 - bankWidth, centerZ + 28 + bankWidth
      );
      bankShape.bezierCurveTo(
        centerX - 25, centerZ + 40 + bankWidth,
        centerX + 15, centerZ + 42 + bankWidth,
        centerX + 35 + bankWidth, centerZ + 32 + bankWidth
      );
      bankShape.bezierCurveTo(
        centerX + 48 + bankWidth, centerZ + 20,
        centerX + 46 + bankWidth, centerZ - 8,
        centerX + 32 + bankWidth, centerZ - 22 - bankWidth
      );
      bankShape.bezierCurveTo(
        centerX + 15, centerZ - 30 - bankWidth,
        centerX - 8, centerZ - 32 - bankWidth,
        centerX - 35 - bankWidth, centerZ - 25 - bankWidth
      );

      const bankGeometry = new THREE.ShapeGeometry(bankShape);
      const bankMaterial = new THREE.MeshPhongMaterial({
        color: 0x7cb342,
        shininess: 30,
      });
      const bank = new THREE.Mesh(bankGeometry, bankMaterial);
      bank.rotation.x = -Math.PI / 2;
      bank.position.set(0, 0.08, 0);
      scene.add(bank);

      // 水面波纹效果
      const waveGeometry = new THREE.ShapeGeometry(lakeShape);
      const waveMaterial = new THREE.MeshBasicMaterial({
        color: 0x64b5f6,
        transparent: true,
        opacity: 0.3,
        side: THREE.DoubleSide,
      });
      const wave = new THREE.Mesh(waveGeometry, waveMaterial);
      wave.rotation.x = -Math.PI / 2;
      wave.position.set(0, 0.12, 0);
      scene.add(wave);
    };

    // 创建道路系统
    const createRoads = () => {
      const roadMaterial = new THREE.MeshPhongMaterial({
        color: 0x2a2a2a,
        shininess: 30,
      });

      const laneLineMaterial = new THREE.MeshBasicMaterial({
        color: 0xffffff,
        transparent: true,
        opacity: 0.6,
      });

      const centerLineMaterial = new THREE.MeshBasicMaterial({
        color: 0xffff00,
        transparent: true,
        opacity: 0.8,
      });

      ROADS.forEach((z) => {
        const roadGeometry = new THREE.BoxGeometry(700, 0.2, ROAD_WIDTH);
        const road = new THREE.Mesh(roadGeometry, roadMaterial);
        road.position.set(0, 0.1, z);
        scene.add(road);

        const centerLineGeometry = new THREE.BoxGeometry(700, 0.25, 0.4);
        const centerLine = new THREE.Mesh(centerLineGeometry, centerLineMaterial);
        centerLine.position.set(0, 0.2, z);
        scene.add(centerLine);

        for (let x = -340; x < 340; x += 20) {
          const dashGeometry = new THREE.BoxGeometry(10, 0.25, 0.2);
          const dash = new THREE.Mesh(dashGeometry, laneLineMaterial);
          dash.position.set(x, 0.2, z);
          scene.add(dash);
        }
      });

      ROADS.forEach((x) => {
        const roadGeometry = new THREE.BoxGeometry(ROAD_WIDTH, 0.2, 700);
        const road = new THREE.Mesh(roadGeometry, roadMaterial);
        road.position.set(x, 0.1, 0);
        scene.add(road);

        const centerLineGeometry = new THREE.BoxGeometry(0.4, 0.25, 700);
        const centerLine = new THREE.Mesh(centerLineGeometry, centerLineMaterial);
        centerLine.position.set(x, 0.2, 0);
        scene.add(centerLine);

        for (let z = -340; z < 340; z += 20) {
          const dashGeometry = new THREE.BoxGeometry(0.2, 0.25, 10);
          const dash = new THREE.Mesh(dashGeometry, laneLineMaterial);
          dash.position.set(x, 0.2, z);
          scene.add(dash);
        }
      });
    };

    // 创建3D小汽车模型
    const createCarModel = (color: number) => {
      const carGroup = new THREE.Group();

      const bodyGeometry = new THREE.BoxGeometry(4, 1.5, 8);
      const bodyMaterial = new THREE.MeshPhongMaterial({
        color: color,
        shininess: 100,
      });
      const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
      body.position.y = 0.75;
      carGroup.add(body);

      const roofGeometry = new THREE.BoxGeometry(3.5, 1, 5);
      const roof = new THREE.Mesh(roofGeometry, bodyMaterial);
      roof.position.y = 1.75;
      roof.position.z = -0.5;
      carGroup.add(roof);

      const windowMaterial = new THREE.MeshPhongMaterial({
        color: 0x88ccff,
        transparent: true,
        opacity: 0.6,
        shininess: 150,
      });

      const frontWindowGeometry = new THREE.PlaneGeometry(3.3, 0.8);
      const frontWindow = new THREE.Mesh(frontWindowGeometry, windowMaterial);
      frontWindow.position.set(0, 1.8, 1.5);
      frontWindow.rotation.x = -0.2;
      carGroup.add(frontWindow);

      const backWindow = frontWindow.clone();
      backWindow.position.z = -3;
      backWindow.rotation.x = 0.2;
      carGroup.add(backWindow);

      const wheelGeometry = new THREE.CylinderGeometry(0.5, 0.5, 0.4, 16);
      const wheelMaterial = new THREE.MeshPhongMaterial({ color: 0x222222 });

      const wheelPositions = [
        [-1.8, 0.5, 2.5],
        [1.8, 0.5, 2.5],
        [-1.8, 0.5, -2.5],
        [1.8, 0.5, -2.5],
      ];

      wheelPositions.forEach((pos) => {
        const wheel = new THREE.Mesh(wheelGeometry, wheelMaterial);
        wheel.rotation.z = Math.PI / 2;
        wheel.position.set(pos[0], pos[1], pos[2]);
        carGroup.add(wheel);
      });

      const headlightGeometry = new THREE.SphereGeometry(0.3, 8, 8);
      const headlightMaterial = new THREE.MeshBasicMaterial({
        color: 0xffffee,
        transparent: true,
        opacity: 0.9,
      });

      const headlight1 = new THREE.Mesh(headlightGeometry, headlightMaterial);
      headlight1.position.set(-1.3, 0.8, 4);
      carGroup.add(headlight1);

      const headlight2 = headlight1.clone();
      headlight2.position.set(1.3, 0.8, 4);
      carGroup.add(headlight2);

      const taillightMaterial = new THREE.MeshBasicMaterial({
        color: 0xff3333,
        transparent: true,
        opacity: 0.8,
      });

      const taillight1 = new THREE.Mesh(headlightGeometry, taillightMaterial);
      taillight1.position.set(-1.3, 0.8, -4);
      carGroup.add(taillight1);

      const taillight2 = taillight1.clone();
      taillight2.position.set(1.3, 0.8, -4);
      carGroup.add(taillight2);

      return carGroup;
    };

    // 创建信号灯
    const createTrafficLights = () => {
      const intersections = [
        { x: -240, z: -240 }, { x: -240, z: -80 }, { x: -240, z: 80 }, { x: -240, z: 240 },
        { x: -80, z: -240 }, { x: -80, z: -80 }, { x: -80, z: 80 }, { x: -80, z: 240 },
        { x: 80, z: -240 }, { x: 80, z: -80 }, { x: 80, z: 80 }, { x: 80, z: 240 },
        { x: 240, z: -240 }, { x: 240, z: -80 }, { x: 240, z: 80 }, { x: 240, z: 240 },
      ];

      intersections.forEach((pos, index) => {
        const lightGroup = new THREE.Group();

        const poleGeometry = new THREE.CylinderGeometry(0.3, 0.3, 8, 8);
        const poleMaterial = new THREE.MeshPhongMaterial({ color: 0x444444 });
        const pole = new THREE.Mesh(poleGeometry, poleMaterial);
        pole.position.y = 4;
        lightGroup.add(pole);

        const boxGeometry = new THREE.BoxGeometry(1, 4, 0.5);
        const boxMaterial = new THREE.MeshPhongMaterial({ color: 0x1a1a1a });
        const box = new THREE.Mesh(boxGeometry, boxMaterial);
        box.position.set(0, 8, 0);
        lightGroup.add(box);

        const redGeometry = new THREE.SphereGeometry(0.4, 12, 12);
        const redMaterial = new THREE.MeshBasicMaterial({
          color: 0xff0000,
          transparent: true,
          opacity: 0.3,
        });
        const redLight = new THREE.Mesh(redGeometry, redMaterial);
        redLight.position.set(0, 9, 0.3);
        redLight.name = "red";
        lightGroup.add(redLight);

        const yellowMaterial = new THREE.MeshBasicMaterial({
          color: 0xffff00,
          transparent: true,
          opacity: 0.3,
        });
        const yellowLight = new THREE.Mesh(redGeometry, yellowMaterial);
        yellowLight.position.set(0, 8, 0.3);
        yellowLight.name = "yellow";
        lightGroup.add(yellowLight);

        const greenMaterial = new THREE.MeshBasicMaterial({
          color: 0x00ff00,
          transparent: true,
          opacity: 0.3,
        });
        const greenLight = new THREE.Mesh(redGeometry, greenMaterial);
        greenLight.position.set(0, 7, 0.3);
        greenLight.name = "green";
        lightGroup.add(greenLight);

        lightGroup.position.set(pos.x + 12, 0, pos.z + 12);
        scene.add(lightGroup);

        const controlsHorizontal = index % 2 === 0;
        trafficLights.push({
          mesh: lightGroup,
          state: controlsHorizontal ? "green" : "red",
          timer: 0,
          position: new THREE.Vector3(pos.x, 0, pos.z),
          controlsHorizontal: controlsHorizontal,
        });
      });
    };

    // 检查与前方车辆的距离
    const getDistanceToFrontVehicle = (vehicle: Vehicle): number => {
      let minDistance = Infinity;

      for (const otherVehicle of vehicles) {
        if (otherVehicle === vehicle) continue;

        // 只检查同车道同方向的车辆
        if (
          vehicle.lane.road === otherVehicle.lane.road &&
          vehicle.lane.direction === otherVehicle.lane.direction &&
          vehicle.lane.isHorizontal === otherVehicle.lane.isHorizontal
        ) {
          let distance = 0;

          if (vehicle.lane.isHorizontal) {
            if (vehicle.lane.direction === "forward") {
              // 向右行驶，检查右侧车辆
              if (otherVehicle.mesh.position.x > vehicle.mesh.position.x) {
                distance = otherVehicle.mesh.position.x - vehicle.mesh.position.x;
              }
            } else {
              // 向左行驶，检查左侧车辆
              if (otherVehicle.mesh.position.x < vehicle.mesh.position.x) {
                distance = vehicle.mesh.position.x - otherVehicle.mesh.position.x;
              }
            }
          } else {
            if (vehicle.lane.direction === "forward") {
              // 向下行驶，检查下方车辆
              if (otherVehicle.mesh.position.z > vehicle.mesh.position.z) {
                distance = otherVehicle.mesh.position.z - vehicle.mesh.position.z;
              }
            } else {
              // 向上行驶，检查上方车辆
              if (otherVehicle.mesh.position.z < vehicle.mesh.position.z) {
                distance = vehicle.mesh.position.z - otherVehicle.mesh.position.z;
              }
            }
          }

          if (distance > 0 && distance < minDistance) {
            minDistance = distance;
          }
        }
      }

      return minDistance;
    };

    // 创建车辆 - 优化初始位置避免重叠
    const createVehicles = () => {
      const carColors = [0xff6b6b, 0x4ecdc4, 0x45b7d1, 0xf9ca24, 0x6c5ce7, 0xa29bfe, 0xfd79a8, 0x00b894];
      const vehicleCount = 50;

      // 按车道分组存储已有车辆的位置，避免初始重叠
      const occupiedPositions: Map<string, number[]> = new Map();

      for (let i = 0; i < vehicleCount; i++) {
        const color = carColors[Math.floor(Math.random() * carColors.length)];
        const car = createCarModel(color);

        const roadIndex = Math.floor(Math.random() * ROADS.length);
        const isHorizontal = Math.random() > 0.5;
        const laneDirection = Math.random() > 0.5 ? "forward" : "backward";
        const laneOffset = laneDirection === "forward" ? -5 : 5;

        // 生成车道标识符
        const laneKey = `${roadIndex}-${isHorizontal ? 'h' : 'v'}-${laneDirection}`;
        if (!occupiedPositions.has(laneKey)) {
          occupiedPositions.set(laneKey, []);
        }
        const lanePositions = occupiedPositions.get(laneKey)!;

        let position = 0;
        let attempts = 0;
        const maxAttempts = 20;

        // 尝试找到一个不重叠的位置
        do {
          position = Math.random() * 600 - 300;
          attempts++;

          // 检查是否与同车道的其他车辆位置冲突
          const tooClose = lanePositions.some(pos => Math.abs(pos - position) < MIN_VEHICLE_SPACING);

          if (!tooClose || attempts >= maxAttempts) {
            break;
          }
        } while (attempts < maxAttempts);

        lanePositions.push(position);

        if (isHorizontal) {
          car.position.set(
            position,
            1,
            ROADS[roadIndex] + laneOffset
          );
          car.rotation.y = laneDirection === "forward" ? Math.PI / 2 : -Math.PI / 2;
        } else {
          car.position.set(
            ROADS[roadIndex] + laneOffset,
            1,
            position
          );
          car.rotation.y = laneDirection === "forward" ? 0 : Math.PI;
        }

        scene.add(car);

        const direction = new THREE.Vector3();
        if (isHorizontal) {
          direction.set(laneDirection === "forward" ? 1 : -1, 0, 0);
        } else {
          direction.set(0, 0, laneDirection === "forward" ? 1 : -1);
        }

        const baseSpeed = 0.4 + Math.random() * 0.3; // 速度范围更合理
        vehicles.push({
          mesh: car,
          speed: baseSpeed,
          baseSpeed: baseSpeed,
          direction: direction,
          lane: { road: roadIndex, direction: laneDirection, isHorizontal: isHorizontal },
          isStopped: false,
        });
      }
    };

    // 更新信号灯
    const updateTrafficLights = () => {
      trafficLights.forEach((light) => {
        light.timer++;

        if (light.state === "green" && light.timer > 120) {
          light.state = "yellow";
          light.timer = 0;
        } else if (light.state === "yellow" && light.timer > 30) {
          light.state = "red";
          light.timer = 0;
        } else if (light.state === "red" && light.timer > 120) {
          light.state = "green";
          light.timer = 0;
        }

        const redLight = light.mesh.getObjectByName("red") as THREE.Mesh;
        const yellowLight = light.mesh.getObjectByName("yellow") as THREE.Mesh;
        const greenLight = light.mesh.getObjectByName("green") as THREE.Mesh;

        if (redLight && yellowLight && greenLight) {
          (redLight.material as THREE.MeshBasicMaterial).opacity = light.state === "red" ? 1 : 0.3;
          (yellowLight.material as THREE.MeshBasicMaterial).opacity = light.state === "yellow" ? 1 : 0.3;
          (greenLight.material as THREE.MeshBasicMaterial).opacity = light.state === "green" ? 1 : 0.3;
        }
      });
    };

    // 检查车辆是否应该停车（信号灯）
    const shouldStopAtLight = (vehicle: Vehicle): boolean => {
      const pos = vehicle.mesh.position;
      const stopDistance = 25;

      for (const light of trafficLights) {
        const dx = Math.abs(pos.x - light.position.x);
        const dz = Math.abs(pos.z - light.position.z);

        if (dx < stopDistance && dz < stopDistance) {
          if (vehicle.lane.isHorizontal && light.controlsHorizontal) {
            if (vehicle.lane.direction === "forward" && pos.x < light.position.x && pos.x > light.position.x - stopDistance) {
              return light.state === "red" || light.state === "yellow";
            }
            if (vehicle.lane.direction === "backward" && pos.x > light.position.x && pos.x < light.position.x + stopDistance) {
              return light.state === "red" || light.state === "yellow";
            }
          }
          else if (!vehicle.lane.isHorizontal && !light.controlsHorizontal) {
            if (vehicle.lane.direction === "forward" && pos.z < light.position.z && pos.z > light.position.z - stopDistance) {
              return light.state === "red" || light.state === "yellow";
            }
            if (vehicle.lane.direction === "backward" && pos.z > light.position.z && pos.z < light.position.z + stopDistance) {
              return light.state === "red" || light.state === "yellow";
            }
          }
        }
      }
      return false;
    };

    // 更新车辆
    const updateVehicles = () => {
      vehicles.forEach((vehicle) => {
        const shouldStopLight = shouldStopAtLight(vehicle);
        const distanceToFront = getDistanceToFrontVehicle(vehicle);
        const shouldStopCar = distanceToFront < SAFE_DISTANCE;

        // 平滑的加速和减速
        if (shouldStopLight || shouldStopCar) {
          // 根据距离计算减速率 - 距离越近减速越快
          const decelerationRate = shouldStopCar && distanceToFront < SAFE_DISTANCE * 2
            ? 0.08
            : 0.04;
          vehicle.speed = Math.max(0, vehicle.speed - decelerationRate);
          vehicle.isStopped = true;
        } else if (vehicle.isStopped) {
          // 平滑恢复速度
          vehicle.speed = Math.min(vehicle.baseSpeed, vehicle.speed + 0.02);
          if (vehicle.speed >= vehicle.baseSpeed * 0.95) {
            vehicle.isStopped = false;
          }
        }

        vehicle.mesh.position.add(vehicle.direction.clone().multiplyScalar(vehicle.speed));

        // 更符合物理常识的边界处理 - 车辆在视野外重新生成
        const boundary = 360;
        if (vehicle.lane.isHorizontal) {
          if (vehicle.lane.direction === "forward" && vehicle.mesh.position.x > boundary) {
            vehicle.mesh.position.x = -boundary;
          } else if (vehicle.lane.direction === "backward" && vehicle.mesh.position.x < -boundary) {
            vehicle.mesh.position.x = boundary;
          }
        } else {
          if (vehicle.lane.direction === "forward" && vehicle.mesh.position.z > boundary) {
            vehicle.mesh.position.z = -boundary;
          } else if (vehicle.lane.direction === "backward" && vehicle.mesh.position.z < -boundary) {
            vehicle.mesh.position.z = boundary;
          }
        }
      });
    };

    // 动画循环
    const animate = () => {
      animationId = requestAnimationFrame(animate);
      updateTrafficLights();
      updateVehicles();
      controls.update();
      renderer.render(scene, camera);
    };

    // 初始化场景
    const initScene = () => {
      if (!containerRef.value) return;

      scene = new THREE.Scene();
      scene.background = new THREE.Color(0x001a33);
      scene.fog = new THREE.Fog(0x001a33, 250, 700);

      camera = new THREE.PerspectiveCamera(
        55,
        containerRef.value.clientWidth / containerRef.value.clientHeight,
        0.1,
        1500
      );
      camera.position.set(250, 200, 250);
      camera.lookAt(0, 0, 0);

      renderer = new THREE.WebGLRenderer({ antialias: true });
      renderer.setSize(containerRef.value.clientWidth, containerRef.value.clientHeight);
      renderer.setPixelRatio(window.devicePixelRatio);
      containerRef.value.appendChild(renderer.domElement);

      controls = new OrbitControls(camera, renderer.domElement);
      controls.enableDamping = true;
      controls.dampingFactor = 0.05;
      controls.minDistance = 100;
      controls.maxDistance = 600;
      controls.maxPolarAngle = Math.PI / 2.1;

      // 光照
      const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
      scene.add(ambientLight);

      const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
      directionalLight.position.set(150, 200, 150);
      scene.add(directionalLight);

      const pointLight1 = new THREE.PointLight(0x4a9eff, 0.6, 400);
      pointLight1.position.set(-150, 100, -150);
      scene.add(pointLight1);

      const pointLight2 = new THREE.PointLight(0xffd700, 0.6, 400);
      pointLight2.position.set(150, 100, 150);
      scene.add(pointLight2);

      // 创建场景元素
      createLake(); // 园区中心湖泊
      createRoads();
      createParkBuildings();
      createTrafficLights();
      createVehicles();

      const handleResize = () => {
        if (!containerRef.value) return;
        camera.aspect = containerRef.value.clientWidth / containerRef.value.clientHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(containerRef.value.clientWidth, containerRef.value.clientHeight);
      };
      window.addEventListener("resize", handleResize);

      animate();

      return () => {
        window.removeEventListener("resize", handleResize);
      };
    };

    onMounted(() => {
      initScene();
    });

    onUnmounted(() => {
      if (animationId) {
        cancelAnimationFrame(animationId);
      }
      if (renderer) {
        renderer.dispose();
      }
    });

    return () => (
      <div class="city-scene-3d">
        <div class="city-scene-3d__container" ref={containerRef}></div>
        <div class="city-scene-3d__info">
          <div class="city-scene-3d__tip">
            🏢 科技园区数字孪生 | 💼 智慧园区 | 💧 景观湖泊 | 🚗 智能车辆防撞 | 🚦 遵守交规 | 🖱️ 交互控制
          </div>
        </div>
      </div>
    );
  },
});
